﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TestSimulator.ServiceReference1;

namespace TestSimulator
{
    public delegate void WaterValue(double value);

    class WaterThread
    {
        private WaterMonitor _m;
        private readonly Random _random;
        private DateTime _now;
        private int _min, _max;
        public bool IsRaining;
        public bool Simulate { get; set; } //start/stop simulator
        public int StationId { get; private set; }
        private Dictionary<int, double> _pumps; //id, capacity

        /// <summary>
        /// 
        /// </summary>
        /// <param name="monitor">Monitor is needed to access events</param>
        /// <param name="minRainValue">min value for rain</param>
        /// <param name="maxRainValue">max value for rain</param>
        public WaterThread(WaterMonitor monitor, int stationId, Dictionary<int, double> pumps, int minRainValue, int maxRainValue)
        {
            _m = monitor;
            StationId = stationId;
            _pumps = pumps;
            _min = minRainValue;
            _max = maxRainValue;
            _random = new Random();
            _now = DateTime.Now;
            IsRaining = false;
            Simulate = true;
        }

        public void Rain()
        {
            int i = 0, max = _max;

            DateTime date = DateTime.Now;
            while (Simulate)
            {
                if (IsRaining) //already raining, continue or stop rain?
                {
                    if (_random.Next(0, 5) < 4) { i = _random.Next(1, max); }
                    else { IsRaining = false; }
                }
                else
                {
                    if (_random.Next(0, 10) > 8) //the chance of rain is rather small compaired to the dry hours
                    {
                        i = _random.Next(_min, _max);
                        max = i;
                        IsRaining = true;
                    }
                    else { IsRaining = false; }
                }
                _m.Enqueue(i);
                Thread.Sleep(1000);
            }
        }

        public void Drain(object id)
        {
            while (Simulate)
            {
                _m.Dequeue(_pumps[(int)id]);
                Thread.Sleep(1000);
            }
        }
    }
}